import {request, post } from "@/utils/request";
import type {Ref} from "vue";
import {ElMessage} from "element-plus";
import ApiResult from "@/api/base/ApiResult";
import {IGoodsPageRow} from "@/api/modules/pointsMall";

export function useEditGoods() {
  const form = reactive({})
  const formRef = ref()
  const initialDetailText = ref('')
  const initialDescText = ref('')

  const getDetail = (row: IGoodsPageRow, formProps: string[]) => {
    Object.keys(row).forEach(key => {
      form[key] = row[key]
    })
    initialDetailText.value = row.detailText
    initialDescText.value=row.description

    formatDetail()
  }

  const isEmpty = (val: any) => {
    return val === undefined || val === null || val === ''
  }

  const formatDetail = () => {
    // TODO 比如价格显示需要做初始转化
  }

  const formatForm = (formProps: string[]) => {
    const _form = JSON.parse(JSON.stringify(form))

    if (formProps.includes('')) { // TODO
      _form[''] = form['']
    }
    // TODO 在此 添加更多 FormItem 的格式化
    return _form
  }

  const submitForm = async (url: string, data: any, options?:any) => {
    return new Promise((resolve) => {
      formRef.value?.validate(async (valid:any, fields:any) => {
        if (valid) {
          const rs:ApiResult<any> = await request(url, data)

          if (rs.code === 200) {
            ElMessage.success('保存成功')
            resolve(rs)
          }
        }
      })
    })
  }

  const isShowEditGoods:Ref<boolean> = ref(false)
  const currentEditingRow:Ref<IGoodsPageRow | undefined> = ref<IGoodsPageRow>()
  const showEditGoods = (rowData: IGoodsPageRow) => {
    currentEditingRow.value = rowData
    isShowEditGoods.value = true
  }

  return {
    form,
    initialDetailText,
    initialDescText,
    formRef,
    getDetail,
    formatForm,
    submitForm,

    isShowEditGoods,
    currentEditingRow,
    showEditGoods
  }
}
